package org.csu.mypetstore.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.entity.*;
import org.csu.mypetstore.api.persistence.LineItemMapper;
import org.csu.mypetstore.api.persistence.OrderMapper;
import org.csu.mypetstore.api.persistence.SequenceMapper;
import org.csu.mypetstore.api.pojo.Cart;
import org.csu.mypetstore.api.entity.Sequence;
import org.csu.mypetstore.api.service.AccountService;
import org.csu.mypetstore.api.service.CartService;
import org.csu.mypetstore.api.service.CatalogService;
import org.csu.mypetstore.api.service.OrderService;
import org.csu.mypetstore.api.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private SequenceMapper sequenceMapper;

    @Autowired
    private LineItemMapper lineItemMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private CatalogService catalogService;

//    @Autowired
//    private LineItemMa

    @Autowired
    private CartService cartService;

    public CommonResponse<OrderVO> generateOrder(
            String shipAddr1,
            String shipAddr2,
            String shipCity,
            String shipState,
            String shipZip,
            String shipCountry,
            String billAddr1,
            String billAddr2,
            String billCity,
            String billState,
            String billZip,
            String billCountry,
            String courier,
            String billtofirstname,
            String billtolastname,
            String shiptofirstname,
            String shiptolastname,
            String creditcard,
            String cardtype,
            String expiryDate,
            String locale,
            String userid,
            HttpSession session){
//        取得获得购物车的数据
        CommonResponse<CartVO> response = cartService.viewCart(session);
        CartVO cartVO = response.getData();
//        将session中的购物车清空
        Cart cart = new Cart();
        session.setAttribute("cart",cart);
        Order order = new Order();
//        获得下一个订单号
        order.setOrderId(getNextId("ordernum"));
//      将lineItem注入order中
        List<CartItemVO> cartItemVOList = cartVO.getItemVOList();
        int lineNum = 1;
        for(CartItemVO cartItemVO: cartItemVOList){
            LineItem lineItem = new LineItem();
            lineItem.setItemId(cartItemVO.getItemID());
            lineItem.setOrderId(order.getOrderId());
            lineItem.setLineNumber(lineNum++);
            lineItem.setQuantity(cartItemVO.getQuantity());
            lineItem.setUnitPrice(cartItemVO.getListPrice());
            order.addLineItem(lineItem);
        }
//        设置order的其他属性
        AccountVO accountVO = accountService.getAccount((String)session.getAttribute("username")).getData();
        order.setUsername(accountVO.getUsername());
        Date date = new Date();
        order.setOrderDate(date);
        System.out.println("orderserviceImpl:97:设置的date"+date);
        order.setShipAddress1(shipAddr1);
        order.setShipAddress2(shipAddr2);
        order.setShipCity(shipCity);
        order.setShipState(shipState);
        order.setShipZip(shipZip);
        order.setShipCountry(shipCountry);
        order.setBillAddress1(billAddr1);
        order.setBillAddress2(billAddr2);
        order.setBillCity(billCity);
        order.setBillState(billState);
        order.setBillZip(billZip);
        order.setBillCountry(billCountry);
        order.setCourier(courier);
        order.setTotalPrice(cartVO.getTotalCost());
        order.setBillToFirstName(billtofirstname);
        order.setBillToLastName(billtolastname);
        order.setShipToFirstName(shiptofirstname);
        order.setShipToLastName(shiptolastname);
        order.setCreditCard(creditcard);
        order.setExpiryDate(expiryDate);
        order.setCardType(cardtype);
        order.setLocale(locale);
        order.setAlreadyShipped(0);
        orderMapper.insert(order);
//        插入lineItem表
        for (int i = 0; i < order.getLineItems().size(); i++) {
            LineItem lineItem = (LineItem) order.getLineItems().get(i);
            lineItemMapper.insert(lineItem);
        }

        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(order.getOrderId());
        orderVO.setOrderDate(date);
        orderVO.setCarType(cardtype);
        orderVO.setExpiryDate(expiryDate);
        orderVO.setBillFirstName(billtofirstname);
        orderVO.setBillLastName(billtolastname);
        orderVO.setBillAddress1(billAddr1);
        orderVO.setBillAddress2(billAddr2);
        orderVO.setBillCity(billCity);
        orderVO.setBillState(billState);
        orderVO.setBillZip(billZip);
        orderVO.setBillCountry(billCountry);
        orderVO.setShipFirstName(shiptofirstname);
        orderVO.setShipLastName(shiptolastname);
        orderVO.setShipAddress1(shipAddr1);
        orderVO.setShipAddress2(shipAddr2);
        orderVO.setShipCity(shipCity);
        orderVO.setShipState(shipState);
        orderVO.setShipZip(shipZip);
        orderVO.setShipCountry(shipCountry);
        orderVO.setShipCourier("UPS");
        orderVO.setStatus("P");
        orderVO.setCartItemVOList(cartItemVOList);
        orderVO.setTotal(cartVO.getTotalCost());
        return CommonResponse.createForSuccess(orderVO);
    }

    @Override
    public CommonResponse<List<OrderVO>> viewOrders(HttpSession session) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("userid",session.getAttribute("username"));
        List<Order> orderList = orderMapper.selectList(orderQueryWrapper);
        ArrayList<OrderVO> orderVOArrayList = new ArrayList<OrderVO>();
        for(Order order:orderList){
            QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
            lineItemQueryWrapper.eq("orderid",order.getOrderId());
            List<LineItem> lineItemList = lineItemMapper.selectList(lineItemQueryWrapper);

            BigDecimal totalCost = new BigDecimal(0);
            ArrayList<CartItemVO> cartItemVOArrayList = new ArrayList<>();
            for(LineItem lineItem:lineItemList){
                CartItemVO cartItemVO = new CartItemVO();
                cartItemVO.setItemID(lineItem.getItemId());
                Item item = catalogService.getItemByItemid(lineItem.getItemId()).getData();
                cartItemVO.setProductID(item.getProductId());
                Product product = catalogService.getProductByProid(item.getProductId()).getData();
                cartItemVO.setDescription(item.getAttribute1() +" "+ product.getName());
                cartItemVO.setInStock(true);
                cartItemVO.setQuantity(lineItem.getQuantity());
                cartItemVO.setListPrice(lineItem.getUnitPrice());
                cartItemVO.setTotalCost(lineItem.getUnitPrice().multiply(new BigDecimal(lineItem.getQuantity())));
                totalCost = totalCost.add(lineItem.getUnitPrice().multiply(new BigDecimal(lineItem.getQuantity())));
                cartItemVOArrayList.add(cartItemVO);
            }

            OrderVO orderVO = new OrderVO();
            orderVO.setOrderId(order.getOrderId());
            orderVO.setOrderDate(order.getOrderDate());
            System.out.println("orderserviceImpl:97:输出的date"+order.getOrderDate());
            orderVO.setCarType(order.getCardType());
            orderVO.setExpiryDate(order.getExpiryDate());
            orderVO.setBillFirstName(order.getBillToFirstName());
            orderVO.setBillLastName(order.getBillToLastName());
            orderVO.setBillAddress1(order.getBillAddress1());
            orderVO.setBillAddress2(order.getBillAddress2());
            orderVO.setBillCity(order.getBillCity());
            orderVO.setBillState(order.getBillState());
            orderVO.setBillZip(order.getBillZip());
            orderVO.setBillCountry(order.getBillCountry());
            orderVO.setShipFirstName(order.getShipToFirstName());
            orderVO.setShipLastName(order.getShipToLastName());
            orderVO.setShipAddress1(order.getShipAddress1());
            orderVO.setShipAddress2(order.getShipAddress2());
            orderVO.setShipCity(order.getShipCity());
            orderVO.setShipState(order.getShipState());
            orderVO.setShipZip(order.getShipZip());
            orderVO.setShipCountry(order.getShipCountry());
            orderVO.setShipCourier("UPS");
            orderVO.setStatus("P");
            orderVO.setCartItemVOList(cartItemVOArrayList);
            orderVO.setTotal(totalCost);
            orderVOArrayList.add(orderVO);
        }
        return CommonResponse.createForSuccess(orderVOArrayList);
    };

    public int getNextId(String name) {
        System.out.println("OrderServiceImpl:217行"+ name);
        Sequence sequence = sequenceMapper.selectById(name);
        Sequence parameterObject = new Sequence(name, sequence.getNextId() + 1);
        sequenceMapper.updateById(parameterObject);
        return sequence.getNextId();
    }
}
